package com.hulushuju.core.net;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * @Author: Hanjiafeng
 * @Date: 2019-05-28
 * @Desc: 请求对象,包括url,请求方法,请求头
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class HttpRequestImpl {
    private Request.Builder requestBuilder;

    private Headers.Builder headersBuilder;

    /**
     * 初始化
     */
    private HttpRequestImpl initialize() {
        headersBuilder = new Headers.Builder();
        requestBuilder = new Request.Builder();
        return this;
    }

    private HttpRequestImpl url(String url) {
        requestBuilder.url(url);
        return this;
    }

    /**
     * 使用指定的ContentType和postBody进行设置post的RequestBody
     *
     * @param contentType ContentType
     * @param postBody    请求数据
     * @return HttpRequestImpl
     */
    private HttpRequestImpl post(ContentType contentType, String postBody) {
        //todo post是否会设置Content-Type???
//        requestBuilder.header("Content-Type",contentType.getSubType());

        MediaType mediaType = MediaType.parse(contentType.getSubType());
        RequestBody requestBody = RequestBody.create(mediaType, postBody);
        requestBuilder.post(requestBody);
        return this;
    }

    private Request build() {
        return requestBuilder.headers(headersBuilder.build()).build();
    }

    private HttpRequestImpl addHeader(String name, String value) {
        headersBuilder.add(name, value);
        return this;
    }

    private HttpRequestImpl setHeader(String name, String value) {
        headersBuilder.set(name, value);
        return this;
    }

    private HttpRequestImpl getHeader(String name) {
        headersBuilder.get(name);
        return this;
    }

    private HttpRequestImpl removeHeader(String name) {
        headersBuilder.removeAll(name);
        return this;
    }
}
